import "./index.less"
import { Space, Table, Tag, Input, Button, message, TablePaginationConfig, Modal, Form, Switch, Select, Upload, InputNumber, Popconfirm } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { getProTypeList, getProductList, addProduct, uploadFile, editProd, deletProd, buyProduct } from "@/api/product"
import type { UploadFile } from 'antd/es/upload/interface';
import type { UploadProps } from 'antd/es/upload';
import { useEffect, useRef, useState } from "react";
import systme from "@/api/constant"

let searchValue = {
    name: '',
    typeName: '',
    typeId: '',
    pageIndex: 1,
    pageSize: 10
}

interface product_type {
    id: string
    name: string
}
interface productType {
    "id": string,
    "img": string | any,
    "name": string,
    "pageIndex": number,
    "pageSize": number,
    "price": number,
    "saleroom": number,
    "sales": number,
    "stock": number,
    "typeId": string,
    "typeName": string
}

interface options {
    label: string,
    value: string
}

let ProdId: string;

let productInfo: productType;

export default function product() {
    let user = JSON.parse(sessionStorage.getItem("user") as string) as any

    let buyData = {
        userId: user.id,
        userName: user.userName,
        productId: '',
        productName: '',
        count: 1,
        total: 0,
        status:0
    }

    //搜索
    const handlerSearch = (e: any, key: string) => {
        if (key == "typeName") {
            searchValue.typeName = dataType?.find(item => item.value == e)?.label as string
        } else {
            searchValue.name = e.target.value
        }
    }

    const search = () => {
        searchValue.pageIndex = 1
        initProductList()
    }
    const [dataType, setDataType] = useState<options[]>()
    const [data, setData] = useState<productType[]>()
    //初始化
    useEffect(() => {
        getTypeList()
        initProductList()
    }, [])
    const initProductList = (params = searchValue) => {
        setLoading(true)
        getProductList(params).then((res) => {
            if (res.code == 200) {
                setData(res.data.list)
                setConfig({ ...saveValue.current, total: res.data.total })
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
            setLoading(false)
        }).catch(() => {
            message.error(systme.ERROR_MESSAGE)
            setLoading(false)
        })
    }

    const getTypeList = () => {
        getProTypeList({ pageIndex: 1, pageSize: 9999 }).then((res: any) => {
            let formateData = res.data.list.map((item: product_type) => {
                return {
                    label: item.name,
                    value: item.id
                }
            })
            setDataType(formateData)
        }).catch(() => {
            message.error(systme.ERROR_MESSAGE)
        })
    }


    const columns: ColumnsType<productType> = [
        {
            title: '产品名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '图片',
            key: 'img',
            render: (_, record: any) => (
                <Space size="middle">
                    <img src={record.img} alt="" style={{ width: '40px', height: '40px', cursor: 'pointer' }} />
                </Space>
            ),
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',

        },
        {
            title: '类型',
            dataIndex: 'typeName',
            key: 'typeName',

        },
        {
            title: '销售量',
            dataIndex: 'sales',
            key: 'sales',

        },
        {
            title: '销售额',
            dataIndex: 'saleroom',
            key: 'saleroom',

        },
        {
            title: '库存',
            dataIndex: 'stock',
            key: 'stock',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: productType) => (
                <Space size="middle">
                    <a onClick={() => { handlerBuy(record) }} style={{ color: "green" }}>购买</a>
                    {user.account == 'admin'&& <a onClick={() => { handlerEdit(record) }}>编辑</a>}
                    {user.account == 'admin'&&<Popconfirm
                        title="提示"
                        description="是否删除？"
                        onConfirm={() => { deleteProd(record) }}
                        okButtonProps={{ loading: confirmLoading }}
                        onCancel={cancel}
                    >
                        <a style={{ color: 'red' }}  >删除</a>
                    </Popconfirm>}
                </Space>
            ),
        },
    ];
    //购买产品
    console.log(user);
    
    const [isModalOpen3, setIsModalOpen3] = useState<boolean>(false)
    // const [product, setProduct] = useState<productType>() 
    const [totlal,setTotal] = useState<number>()
    const [buyCount,setBuyCount] = useState<number>(0)
     const handlerBuy = (record: productType) => {
        setIsModalOpen3(true)
        productInfo = record
        buyData.count = 1
        setBuyCount(1)
        setTotal(buyData.count * (productInfo as productType).price)
    }
    const handlerBuyProd = () => {
        buyData.productId = (productInfo as productType).id
        buyData.productName = (productInfo as productType).name
        buyData.total = totlal as number
        buyProduct(buyData).then((res) => {
            if (res.code == 200) {
                message.success("购买成功!请在我的订单里查看")
                setIsModalOpen3(false)
                initProductList()
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
                setIsModalOpen3(false)
            }
        }).catch(() => {
            message.error(systme.ERROR_MESSAGE)
            setIsModalOpen3(false)
        })
    }
    const numberChange = (e: number) => {
        buyData.count = e
        setBuyCount(e)
        setTotal(buyData.count * (productInfo as productType).price)
    }
    //删除
    const [confirmLoading, setConfirmLoading] = useState(false);
    const cancel = () => {
        message.info("取消了删除操作")
    }
    const deleteProd = (e: productType) => {
        setConfirmLoading(true)
        deletProd({ id: e.id }).then((res) => {
            if (res.code == 200) {
                message.success("删除成功")
                initProductList()

            } else {
                message.error(res.msg || "删除失败")
            }
            setConfirmLoading(false)
        }).catch((err) => {
            message.error(systme.ERROR_MESSAGE)
            setConfirmLoading(false)
        })
    }
    //编辑
    const handlerEdit = (e: productType) => {
        handdlerEditData(e)
        setTitle("产品编辑")
        form.setFieldsValue(e)
        setIsModalOpen(true)
        ProdId = e.id
    }
    const handlerEditProd = () => {
        form.validateFields().then((values) => {
            values.id = ProdId
            let params;
            if (typeof values.img != 'string') {
                params = handlerFormateForm(values)
            } else {
                params = values
            }
            editProd(params).then((res) => {
                if (res.code == 200) {
                    setIsModalOpen(false)
                    message.success("修改成功")
                    searchValue.pageIndex = 1
                    initProductList()
                } else {
                    message.error("修改失败")
                }
            })
        }).catch(() => {
            message.error(systme.ERROR_MESSAGE)
        })
        setIsModalOpen(false)
    }


    const handdlerEditData = (data: productType) => {
        setFileList([{
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: data.img,
        }])
    }
    const [loading, setLoading] = useState(true)

    const PageChange = (page: number, pageSize: number) => {
        searchValue.pageIndex = page
        searchValue.pageSize = pageSize
        setLoading(true)
        setConfig({ ...saveValue.current, pageSize, current: page })
        initProductList()
    }

    let pageConfig: TablePaginationConfig = {
        position: ['bottomCenter'],
        total: 0,
        showTotal: (total: number) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        pageSize: 10,
        current: 1

    }
    let [config, setConfig] = useState((pageConfig))
    let saveValue = useRef<TablePaginationConfig>()
    useEffect(() => {
        //储存数据
        saveValue.current = config
    }, [config])

    //添加产品
    const [title, setTitle] = useState<string>("添加产品")
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false)

    const handleOk = () => {
        if (title == '添加产品') {
            addProd()
        } else if (title == '产品编辑') {
            handlerEditProd()
        }
    }

    const addProd = () => {
        form.validateFields().then((values) => {
            console.log(values);
            let params = handlerFormateForm(values)
            addProduct(params).then((res) => {
                if (res.code == 200) {
                    setIsModalOpen(false)
                    message.success("添加成功")
                    searchValue.pageIndex = 1
                    initProductList()
                } else {
                    message.error("添加失败")
                }
            })
        }).catch(() => {
            message.error(systme.ERROR_MESSAGE)
        })
        setIsModalOpen(false)
    }

    const handleCancel = () => {
        setIsModalOpen(false)
    }
    const handlerFormateForm = (data: any) => {
        data.img = data.img.file.response.data
        data.typeName = dataType?.find(item => item.value == data.typeId)?.label as string
        return data
    }


    const [form] = Form.useForm();

    const handlerAdd = () => {
        setTitle('添加产品')
        setIsModalOpen(true)
        form.resetFields()
        setFileList([])
    }

    const [fileList, setFileList] = useState<UploadFile[]>([])

    const handleChange: UploadProps['onChange'] = ({ file: newFile, fileList: newFileList }) => {
        // let uploadImg = new FormData()
        // uploadImg.append("uploadFile",newFile.originFileObj as File)
        // console.log(newFileList);
        setFileList(newFileList)

        // console.log(newFileList);

        // uploadFile(uploadImg).then((res)=>{
        //    if(res.code == 200){
        //     // newFile.status = 'done'
        //     // console.log(fileList);

        //    }else{
        //     message.error(systme.ERROR_MESSAGE)
        //    }
        // }).catch((err)=> {
        //     message.error(systme.ERROR_MESSAGE)
        // })
    };

    const handlePreview = (file: UploadFile) => {
        setpriewImg(file.thumbUrl as string || file.url as string)
        setIsModalOpen2(true)
    };

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const [isModalOpen2, setIsModalOpen2] = useState<boolean>(false)
    const [priewImg, setpriewImg] = useState<string>('')





    return (
        <div className="box_views">
            <div className="header flex_a">
                <div className="item">
                    <Input placeholder="请输入产品名" allowClear onChange={(e: unknown) => { handlerSearch(e, 'name') }} />
                </div>
                <div className="item select">
                    <Select
                        style={{ width: 200 }}
                        options={dataType}
                        placeholder="请选择产品类型"
                        onChange={(e: unknown) => { handlerSearch(e, 'typeName') }}
                        allowClear
                    />
                </div>
                <div className="item">
                    <Button type="primary" icon={<SearchOutlined />} size="middle" onClick={search}>查询</Button>
                </div>
                <div className="addBtn">
                  {user.account == 'admin'&&<Button type="primary" icon={<PlusOutlined />} size="middle" onClick={handlerAdd}>添加产品</Button>}
                </div>
            </div>
            <Table columns={columns} dataSource={data} pagination={config} rowKey={item => item.id} loading={loading} />
            <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={800}>
                <div className="flex_j_c">
                    <Form
                        name="basic"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        style={{ width: 700 }}
                        form={form}
                    >
                        <Form.Item
                            label="产品名称"
                            name="name"
                            rules={[{ required: true, message: '请输入产品名称' }]}
                        >
                            <Input placeholder="请输入名称" />
                        </Form.Item>
                        <Form.Item
                            label="产品类型"
                            name="typeId"
                            rules={[{ required: true, message: '请选择类型' }]}
                        >
                            <Select
                                style={{ width: 200 }}
                                options={dataType}
                                placeholder="请选择产品类型"
                            />
                        </Form.Item>
                        <Form.Item
                            label="产品价格"
                            name="price"
                            rules={[{ required: true, message: '请输入价格' }]}
                        >
                            <InputNumber placeholder="请输入价格" min={1} />
                        </Form.Item>
                        <Form.Item
                            label="产品库存量"
                            name="stock"
                            rules={[{ required: true, message: '请输入库存量' }]}
                        >
                            <InputNumber placeholder="请输入库存量" min={0} />
                        </Form.Item>
                        <Form.Item
                            label="产品图片"
                            name="img"
                        >
                            <Upload
                                action={`${import.meta.env.VITE_APP_BASE_URL}pro/upload`}
                                listType="picture-card"
                                fileList={fileList}
                                onChange={handleChange}
                                onPreview={handlePreview}
                                name={'uploadFile'}
                            >
                                {fileList.length >= 1 ? null : uploadButton}
                            </Upload>
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
            <Modal title="预览图" open={isModalOpen2} onOk={() => setIsModalOpen2(false)} onCancel={() => setIsModalOpen2(false)} width={800}>
                <img src={priewImg} alt="" style={{ width: "100%", height: "800px" }} />
            </Modal>
            <Modal title="购买" open={isModalOpen3} onOk={handlerBuyProd} onCancel={() => setIsModalOpen3(false)} okText={'购买'} centered>
                <div className="buy_box">
                    <div className="item">
                       <span> 产品名：</span>{productInfo?.name}
                    </div>
                    <div className="item">
                    <span> 产品价格：</span>{productInfo?.price}
                    </div>
                    <div className="item">
                    <span>  产品类型：</span>{productInfo?.typeName}
                    </div>
                    <div className="item">
                    <span>  库存：</span>{productInfo?.stock}
                    </div>
                    <div className="item">
                    <span>  总价：</span>{totlal}
                    </div>
                    <div className="item">
                    <span>  购买数：</span><InputNumber min={productInfo?.stock!=0?1:0} max={productInfo?.stock} defaultValue={0} disabled={productInfo?.stock==0} value={buyCount} onChange={(e)=>{numberChange(e as number)}} />
                    </div>
                </div>
            </Modal>
        </div>
    )
}